<?php

class MemberTradeAccountBalance extends DataExtension {
	private static $has_many = array(
		'TradeAccounts' => 'TradeAccount'
	);
	
	private static $casting = array(
		'TradeCoinAccountBalance' => 'Currency'
	);
	
	function augmentWrite(&$manipulation) {
        $tables = array_keys($manipulation);
        $version_table = array();
        foreach($tables as $table) {
            $baseDataClass = ClassInfo::baseDataClass($table);

            $isRootClass = ($table == $baseDataClass);
            if($isRootClass && $manipulation[$table]['command'] == 'insert' && isset($manipulation[$table]['id']) && $manipulation[$table]['id']) {
				DB::query("INSERT INTO TradeCoinAccountBalance (MemberID) VALUES (".$manipulation[$table]['id'].")");
            }
        }
    }
	
	function requireDefaultRecords() {
		$result = DB::query("SELECT * FROM Member WHERE ID NOT IN (SELECT MemberID FROM TradeCoinAccountBalance)");
		foreach($result as $item){
			DB::query("INSERT INTO TradeCoinAccountBalance (MemberID) VALUES (".$item['ID'].")");
		}
	}
	
	function updateFieldLabels(&$labels) {
		$labels['TradeAccounts'] = _t('MemberTradeAccountBalance.TRADE_ACCOUNTS', 'Trade Accounts');
	}

	function updateCMSFields(FieldList $fields) {
    	if($this->owner->exists()) {
            $fields->dataFieldByName('TradeAccounts')->getConfig()->removeComponentsByType('GridFieldAddExistingAutocompleter');
        }
	}

	function TradeAccount($trade_setting_id){
		if(!$trade_account = $this->owner->TradeAccounts()->find('TradeSettingID', $trade_setting_id)){
			$trade_account = TradeAccount::create();
			$trade_account->MemberID = $this->owner->ID;
			$trade_account->TradeSettingID = $trade_setting_id;
		}
		return $trade_account;
	}
	
	function getTradeCoinAccountBalance(){
		return Account::get('TradeCoinAccount', $this->owner->ID)->getBalance();
	}
}
?>